<!DOCTYPE html>
<html lang="en"><head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1"><!-- Begin Jekyll SEO tag v2.8.0 -->
<title>0107: D Snippets III - A Practical Observer | gtkDcoding</title>
<meta name="generator" content="Jekyll v4.3.4" />
<meta property="og:title" content="0107: D Snippets III - A Practical Observer" />
<meta name="author" content="Ron Tarrant" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="This GTK Tutorial covers a D-specific implementation of the Observer pattern." />
<meta property="og:description" content="This GTK Tutorial covers a D-specific implementation of the Observer pattern." />
<link rel="canonical" href="http://localhost:4000/posts/0107-dlang-ui-snippets-iii.html" />
<meta property="og:url" content="http://localhost:4000/posts/0107-dlang-ui-snippets-iii.html" />
<meta property="og:site_name" content="gtkDcoding" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2020-04-14T00:00:00-04:00" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:title" content="0107: D Snippets III - A Practical Observer" />
<script type="application/ld+json">
{"@context":"https://schema.org","@type":"BlogPosting","author":{"@type":"Person","name":"Ron Tarrant"},"dateModified":"2020-04-14T00:00:00-04:00","datePublished":"2020-04-14T00:00:00-04:00","description":"This GTK Tutorial covers a D-specific implementation of the Observer pattern.","headline":"0107: D Snippets III - A Practical Observer","mainEntityOfPage":{"@type":"WebPage","@id":"http://localhost:4000/posts/0107-dlang-ui-snippets-iii.html"},"url":"http://localhost:4000/posts/0107-dlang-ui-snippets-iii.html"}</script>
<!-- End Jekyll SEO tag -->
<link rel="stylesheet" href="../assets/main.css">
  <link rel="stylesheet" href="../css/style.css" /><link type="application/atom+xml" rel="alternate" href="http://localhost:4000/feed.xml" title="gtkDcoding" /></head>
<body><header class="site-header" role="banner">

  <div class="wrapper"><a class="site-title" rel="author" href="../">gtkDcoding</a><nav class="site-nav">
        <input type="checkbox" id="nav-trigger" class="nav-trigger" />
        <label for="nav-trigger">
          <span class="menu-icon">
            <svg viewBox="0 0 18 15" width="18px" height="15px">
              <path d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.032C17.335,0,18,0.665,18,1.484L18,1.484z M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.032C17.335,6.031,18,6.696,18,7.516L18,7.516z M18,13.516C18,14.335,17.335,15,16.516,15H1.484 C0.665,15,0,14.335,0,13.516l0,0c0-0.82,0.665-1.483,1.484-1.483h15.032C17.335,12.031,18,12.695,18,13.516L18,13.516z"/>
            </svg>
          </span>
        </label>

        <div class="trigger"><a class="page-link" href="../about.html">About</a><a class="page-link" href="../index-reverse.html">Posts in Date Order</a><a class="page-link" href="../topics.html">Blog Posts by Topic</a></div>
      </nav></div>
</header>
<main class="page-content" aria-label="Content">
      <div class="wrapper">
        <article class="post h-entry" itemscope itemtype="http://schema.org/BlogPosting">
	<header class="post-header">
		<link rel="stylesheet" href="../css/font_size.css" />
		<link rel="stylesheet" href="../css/figure.css" />
		<link rel="stylesheet" href="../css/topics/dlang.css" />  <!-- sub in the tag/topic -->
		<link rel="stylesheet" href="../css/modal.css" />
		<link rel="stylesheet" href="../css/post.css" />
		<link rel="stylesheet" href="../css/mascot_effects.css" />

		
		
		<p class="post-meta">
		<time class="dt-published" datetime="2020-04-14T00:00:00-04:00" itemprop="datePublished">Tuesday, April 14, 2020
		</time>• by <span itemprop="author" itemscope itemtype="http://schema.org/Person"><span class="p-author h-card" itemprop="name">Ron Tarrant</span></span></p>
	</header>

	<div class="post-content e-content" itemprop="articleBody">
		<div class="skew-line"></div>
		<h1 id="0107-d-snippets-iii---a-practical-observer">0107: D Snippets III - A Practical Observer</h1>

<p>Last time, we started with a look at a generic example of an <em>Observer</em> pattern. This time, we’ll pick apart a more practical example in which multiple <em>Observers</em>—a <code class="language-plaintext highlighter-rouge">Button</code>, an <code class="language-plaintext highlighter-rouge">Image</code>, and an <code class="language-plaintext highlighter-rouge">Entry</code>—change their state depending on the state of a watched object.</p>

<h2 id="the-observer-at-work">The Observer at Work</h2>

<!-- 0, 1 -->
<!-- first occurrence of application and terminal screen shots on a single page -->
<div class="screenshot-frame">
	<div class="frame-header">
		Results of this example:
	</div>
	<div class="frame-screenshot">
		<figure>
			<img id="img0" src="../images/screenshots/021_oop/oop_04.png" alt="Current example output" />		<!-- img# -->
			
			<!-- Modal for screenshot -->
			<div id="modal0" class="modal">																	<!-- modal# -->
				<span class="close0">&times;</span>															<!-- close# -->
				<img class="modal-content" id="img00" />															<!-- img## -->
				<div id="caption"></div>
			</div>
			
			<script>
			// Get the modal
			var modal = document.getElementById("modal0");														// modal#
			
			// Get the image and insert it inside the modal - use its "alt" text as a caption
			var img = document.getElementById("img0");															// img#
			var modalImg = document.getElementById("img00");													// img##
			var captionText = document.getElementById("caption");

			img.onclick = function()
			{
			  modal.style.display = "block";
			  modalImg.src = this.src;
			  captionText.innerHTML = this.alt;
			}
			
			// Get the <span> element that closes the modal
			var span = document.getElementsByClassName("close0")[0];											// close#
			
			// When the user clicks on <span> (x), close the modal
			span.onclick = function()
			{ 
				modal.style.display = "none";
			}
			</script>
			<figcaption>
			Current example output
			</figcaption>
		</figure>
	</div>

	<div class="frame-terminal">
		<figure class="right">
			<img id="img1" src="../images/screenshots/021_oop/oop_04_term.png" alt="Current example terminal output" />		<!-- img#, filename -->

			<!-- Modal for terminal shot -->
			<div id="modal1" class="modal">																				<!-- modal# -->
				<span class="close1">&times;</span>																		<!-- close# -->
				<img class="modal-content" id="img11" />																		<!-- img## -->
				<div id="caption"></div>
			</div>
			
			<script>
			// Get the modal
			var modal = document.getElementById("modal1");																	// modal#
			
			// Get the image and insert it inside the modal - use its "alt" text as a caption
			var img = document.getElementById("img1");																		// img#
			var modalImg = document.getElementById("img11");																// img##
			var captionText = document.getElementById("caption");

			img.onclick = function()
			{
			  modal.style.display = "block";
			  modalImg.src = this.src;
			  captionText.innerHTML = this.alt;
			}
			
			// Get the <span> element that closes the modal
			var span = document.getElementsByClassName("close1")[0];														// close#
			
			// When the user clicks on <span> (x), close the modal
			span.onclick = function()
			{ 
				modal.style.display = "none";
			}
			</script>

			<figcaption>
				Current example terminal output (click for enlarged view)
			</figcaption>
		</figure>
	</div>

	<div class="frame-footer">																								<!-- ------------- filename (below) --------- -->
		The code file for this example is available <a href="https://github.com/rontarrant/gtkd_demos/blob/master/021_oop/oop_04_checkbutton_observer.d" target="_blank">here</a>.
	</div>
</div>
<!-- end of snippet for first (1st) occurrence of application and terminal screen shots on a single page -->

<p>The challenge here is that the watched object needs to see all widgets as being a common type. We’ve got a <code class="language-plaintext highlighter-rouge">Button</code>, an <code class="language-plaintext highlighter-rouge">Entry</code>, and an <code class="language-plaintext highlighter-rouge">Image</code>, so if we write the <code class="language-plaintext highlighter-rouge">addObserver()</code> function to accept a <code class="language-plaintext highlighter-rouge">Button</code>, it’s going to have a fit if we pass it anything else. If we, instead, write it to accept a widget (the common ancestor of <code class="language-plaintext highlighter-rouge">Button</code>, <code class="language-plaintext highlighter-rouge">Image</code>, etc.) we don’t gain anything because we still have no mechanism for adding an <code class="language-plaintext highlighter-rouge">update()</code> function to each of the widgets.</p>

<p>Further, that <code class="language-plaintext highlighter-rouge">update()</code> function has to take on a form that’s useful for each widget type. Here’s what it has to do:</p>

<ul>
  <li>for the <code class="language-plaintext highlighter-rouge">Button</code> we need to change the label text which requires calling <code class="language-plaintext highlighter-rouge">setLabel()</code>,</li>
  <li>for obfuscating text in an <code class="language-plaintext highlighter-rouge">Entry</code>, we need to call <code class="language-plaintext highlighter-rouge">setVisibility()</code>, and</li>
  <li>to switch the graphic displayed in an <code class="language-plaintext highlighter-rouge">Image</code> widget, we need to call <code class="language-plaintext highlighter-rouge">setFromFile()</code>.</li>
</ul>

<p>These functions aren’t interchangeable, so <code class="language-plaintext highlighter-rouge">update()</code> needs to be generic at some level so it can take specific action(s) for each widget we add it to.</p>

<p>What do we do? This is <em>OOP 101</em>. We make <em>Observer</em> an <code class="language-plaintext highlighter-rouge">interface</code> so we can:</p>

<ul>
  <li>have all observing widgets inherit from the <em>Observer</em> <code class="language-plaintext highlighter-rouge">interface</code>,</li>
  <li>define an empty <code class="language-plaintext highlighter-rouge">update()</code> function within the <code class="language-plaintext highlighter-rouge">interface</code> which forces each inheriting widget to implement its own version of it, and</li>
  <li>cast all widgets to type <em>Observer</em> as we add them to the list of <em>Observers</em> so we don’t need to write an override for each widget type.</li>
</ul>

<p>Casting everything to <em>Observer</em> like this works because the only commonality we need between <em>Observers</em> is the <code class="language-plaintext highlighter-rouge">update()</code> function and that’s what’s provided by the <em>Observer</em> interface.</p>

<h3 id="the-observer-interface">The Observer Interface</h3>

<p>So, here’s what our <em>Observer</em> now looks like:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">interface</span> <span class="n">Observer</span>
<span class="p">{</span>
	<span class="kt">void</span> <span class="n">update</span><span class="p">(</span><span class="kt">bool</span> <span class="n">value</span><span class="p">);</span>
	
<span class="p">}</span> <span class="c1">// interface Observer</span>
</code></pre></div></div>

<p>We just need to tell it what we expect for arguments and a return value for the <code class="language-plaintext highlighter-rouge">update()</code> function and that’s that.</p>

<p>Now let’s take a look at the watched object so we have some idea of the requirements of the <code class="language-plaintext highlighter-rouge">update()</code> function.</p>

<h3 id="the-watchedbutton">The WatchedButton</h3>

<p>Here’s the code:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="n">WatchedButton</span> <span class="p">:</span> <span class="n">CheckButton</span>
<span class="p">{</span>
	<span class="nb">string</span> <span class="n">buttonText</span> <span class="p">=</span> <span class="s">"Switch Output"</span><span class="p">;</span>
	<span class="n">Observer</span><span class="p">[]</span> <span class="n">observers</span><span class="p">;</span>
	
	<span class="k">this</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="k">super</span><span class="p">(</span><span class="n">buttonText</span><span class="p">);</span>
		<span class="n">addOnClicked</span><span class="p">(&amp;</span><span class="n">updateAll</span><span class="p">);</span>
		
	<span class="p">}</span> <span class="c1">// this()</span>
	
	
	<span class="kt">void</span> <span class="n">addObserver</span><span class="p">(</span><span class="n">Observer</span> <span class="n">observer</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">observers</span> <span class="p">~=</span> <span class="n">observer</span><span class="p">;</span>
		
	<span class="p">}</span> <span class="c1">// addObserver()</span>
	
	
	<span class="kt">void</span> <span class="n">updateAll</span><span class="p">(</span><span class="n">Button</span> <span class="n">b</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="k">foreach</span><span class="p">(</span><span class="n">observer</span><span class="p">;</span> <span class="n">observers</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">observer</span><span class="p">.</span><span class="n">update</span><span class="p">(</span><span class="n">getActive</span><span class="p">());</span>
			
		<span class="p">}</span>
		
	<span class="p">}</span> <span class="c1">// updateAll()</span>

<span class="p">}</span> <span class="c1">// class WatchedButton</span>
</code></pre></div></div>

<p>The first thing you may notice is that the <code class="language-plaintext highlighter-rouge">change()</code> function is gone. We don’t need it because, instead, we’re hooking up the <code class="language-plaintext highlighter-rouge">updateAll()</code> function to the <code class="language-plaintext highlighter-rouge">onClicked</code> signal. Whenever the state of the <code class="language-plaintext highlighter-rouge">CheckButton</code> changes, <code class="language-plaintext highlighter-rouge">updateAll()</code> runs through the list of observers, calls <code class="language-plaintext highlighter-rouge">update()</code> for each, and passes along the current state of the <code class="language-plaintext highlighter-rouge">CheckButton</code>.</p>

<p>Now let’s look at one of the Widgets that will hear from the watched object.</p>

<h3 id="the-observerbutton---preamble">The ObserverButton - Preamble</h3>

<p>Firstly, what’s going to react to the changing state of the watched object? Let’s make it really obvious and change the label text. For this, we can use a string array. And let’s make things simple by pairing the zeroth element with the <code class="language-plaintext highlighter-rouge">CheckButton</code>’s <code class="language-plaintext highlighter-rouge">false</code> state and the first element with <code class="language-plaintext highlighter-rouge">true</code>, 0 for 0, 1 for 1:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">string</span><span class="p">[]</span> <span class="n">labels</span> <span class="p">=</span> <span class="p">[</span><span class="s">"Take Action"</span><span class="p">,</span> <span class="s">"Don't Take Action"</span><span class="p">];</span>
</code></pre></div></div>

<p>Naturally, one of these will need to be selected as the default and we take care of that in…</p>

<h3 id="the-observerbutton--constructor">The ObserverButton – Constructor</h3>

<p>This is also short-n-sweet:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">this</span><span class="p">()</span>
<span class="p">{</span>
	<span class="k">super</span><span class="p">(</span><span class="n">labels</span><span class="p">[</span><span class="mi">0</span><span class="p">]);</span>
	<span class="n">addOnClicked</span><span class="p">(&amp;</span><span class="n">doSomething</span><span class="p">);</span>
		
<span class="p">}</span> <span class="c1">// this()</span>
</code></pre></div></div>

<p>We set our default label and hook up the <code class="language-plaintext highlighter-rouge">Button</code>’s callback. Now, the callback will do something different based on which label is current, but we’ll get to that momentarily. First, let’s look at…</p>

<h3 id="the-observerbutton--update-function">The ObserverButton – update() Function</h3>

<p>This is the locally-implemented version of the <code class="language-plaintext highlighter-rouge">update()</code> function we declared in the <em>Observer</em> interface. This is where we change the label text.</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">update</span><span class="p">(</span><span class="kt">bool</span> <span class="n">state</span><span class="p">)</span>
<span class="p">{</span>
	<span class="n">setLabel</span><span class="p">(</span><span class="n">labels</span><span class="p">[</span><span class="n">state</span><span class="p">]);</span>
		
<span class="p">}</span> <span class="c1">// updateSubjectState()</span>
</code></pre></div></div>

<h3 id="the-observerbutton--dosomething-function">The ObserverButton – doSomething() Function</h3>

<p>Okay, here it is:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">doSomething</span><span class="p">(</span><span class="n">Button</span> <span class="n">b</span><span class="p">)</span>
<span class="p">{</span>
	<span class="nb">string</span> <span class="n">message</span><span class="p">;</span>

	<span class="k">if</span><span class="p">(</span><span class="n">getLabel</span><span class="p">()</span> <span class="p">==</span> <span class="n">labels</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
	<span class="p">{</span>
		<span class="n">message</span> <span class="p">=</span> <span class="s">"These aren't the droids you're looking for."</span><span class="p">;</span>
	<span class="p">}</span>
	<span class="k">else</span>
	<span class="p">{</span>
		<span class="n">message</span> <span class="p">=</span> <span class="s">"These aren't droids. They're monkeys in tin suits."</span><span class="p">;</span>
	<span class="p">}</span>

	<span class="n">writeln</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
		
<span class="p">}</span> <span class="c1">// doSomething()</span>
</code></pre></div></div>

<p>Based on which of the two label strings is current, we spit out a different terminal message.</p>

<p>Now, let’s take a quick look at how the other <em>Observer</em>-derived objects implement the <code class="language-plaintext highlighter-rouge">update()</code> function…</p>

<h3 id="observerentry">ObserverEntry</h3>

<p>We take the incoming state of the <code class="language-plaintext highlighter-rouge">CheckButton</code> and flip it so that <code class="language-plaintext highlighter-rouge">true</code> becomes <code class="language-plaintext highlighter-rouge">false</code> and vise versa:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">update</span><span class="p">(</span><span class="kt">bool</span> <span class="n">state</span><span class="p">)</span>
<span class="p">{</span>
	<span class="n">state</span> <span class="p">=</span> <span class="p">!</span><span class="n">state</span><span class="p">;</span>
	<span class="n">setVisibility</span><span class="p">(</span><span class="n">state</span><span class="p">);</span>
		
<span class="p">}</span> <span class="c1">// update()</span>
</code></pre></div></div>

<p>This way, visibility is turned on when the <code class="language-plaintext highlighter-rouge">CheckButton</code> is unchecked.</p>

<h3 id="observerimage">ObserverImage</h3>

<p>In the preamble we define two image paths and then write <code class="language-plaintext highlighter-rouge">update()</code> like this:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">update</span><span class="p">(</span><span class="kt">bool</span> <span class="n">state</span><span class="p">)</span>
<span class="p">{</span>
	<span class="k">if</span><span class="p">(</span><span class="n">state</span> <span class="p">==</span> <span class="kc">true</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">current</span> <span class="p">=</span> <span class="n">monkey</span><span class="p">;</span>
	<span class="p">}</span>
	<span class="k">else</span>
	<span class="p">{</span>
		<span class="n">current</span> <span class="p">=</span> <span class="n">robot</span><span class="p">;</span>
	<span class="p">}</span>

	<span class="n">setFromFile</span><span class="p">(</span><span class="n">current</span><span class="p">);</span>
		
<span class="p">}</span> <span class="c1">// update()</span>
</code></pre></div></div>

<p>We hop back and forth between the two image paths, then use <code class="language-plaintext highlighter-rouge">setFromFile()</code> to make the switch.</p>

<h2 id="conclusion">Conclusion</h2>

<p>And there you have it. Each <em>Observer</em>-derived class/object deals with the state of <code class="language-plaintext highlighter-rouge">CheckButton</code> in its own way.</p>

<p>Next time, we’ll take a look at how to handle a list of widgets using <em>D</em>-style arrays. Sounds easy, right? We’ll see.</p>

<div class="blog-nav">
	<div style="float: left;">
		<a href="./0106-dlang-ui-snippets-ii.html">Previous: D Snippets II - Generic Observer</a>
	</div>

	<div style="float: right;">
		<a href="./0108-snippets-iv-arrays.html">Next: Arrays in UI</a>
	</div>
</div>
<p>
	<h3></h3>
<div class="inpage-frame">
	<a href="https://github.com/sponsors/rontarrant">
		<BR>
		<BR>
		<B>Is this article useful? Educational? Entertaining, perhaps?</B>
		<BR>
		<figure class="left">
			<img src="../images/favorite_32.png" alt="Sponsorship heart" style="width: 32px; height: 32px;">
		</figure>
		You're free to accept or decline this invitation to become our newest sponsor.
	</a>
</div>
	<h4 class="comment-blurb"><B>Comments? Questions? Observations?</B></h4>
	<p>
		Did we miss a tidbit of information that would make this post even more informative? Let's talk about it in the comments.
	</p>
	<script src="https://utteranc.es/client.js"
		repo="rontarrant"
		issue-term="pathname"
		theme="github-light"
		crossorigin="anonymous"
		async>
	</script>
	<ul>
		<li> come on over to the <a href="https://forum.dlang.org/">D Language Forum</a> and look for one of the <i>gtkDcoding</i> announcement posts, </li>
		<li> drop by <a href="https://forum.gtkd.org/">the <i>GtkD Forum</i></a>,</li>
		<li> follow the link below to email me, or</li>
		<li> go to the	<a href="https://www.facebook.com">gtkDcoding Facebook page.</a></li>
	</ul>
</p>
<p> You can also subscribe <a href="/feed.xml">via RSS</a> so you won't miss anything. Thank you very much for dropping by.</p>
<p>&copy; Copyright 2025 Ron Tarrant </p>
</div>

	<a class="u-url" href="./0107-dlang-ui-snippets-iii.html" hidden></a>
</article>

      </div>
    </main><footer class="site-footer h-card">
  <data class="u-url" href="/"></data>

  <div class="wrapper">

    <h2 class="footer-heading">gtkDcoding</h2>

    <div class="footer-col-wrapper">
      <div class="footer-col footer-col-1">
        <ul class="contact-list">
          <li class="p-name">Ron Tarrant</li><li><a class="u-email" href="mailto:gtkDcoding@gmail.com">gtkDcoding@gmail.com</a></li></ul>
      </div>

      <div class="footer-col footer-col-2"><ul class="social-media-list"><li><a href="https://github.com/rontarrant"><svg class="svg-icon"><use xlink:href="../assets/minima-social-icons.svg#github"></use></svg> <span class="username">rontarrant</span></a></li></ul>
</div>

      <div class="footer-col footer-col-3">
        <p>Simple examples of how to use GtkD to build GUI applications.</p>
      </div>
    </div>

  </div>

</footer>
</body>

</html>
